<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="产品编码" prop="salesProductNumber">
            <el-select v-model="queryParams.salesProductNumber">
          <el-option
            v-for="item in salesListOptions"
            :key="item.salesId"
            :label="item.salesNumber"
            :value="item.salesId"
          />
        </el-select>
        </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.zc_sales_products"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sales:salesProducts:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sales:salesProducts:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sales:salesProducts:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
          >返回</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="salesProductsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="productId" />
      <el-table-column
        label="产品编码"
        align="center"
        prop="salesProductNumber"
      />
      <el-table-column
        label="产品名称"
        align="center"
        prop="productNumber"
        width="280"
      >
        <template slot-scope="scope">{{
          getProductName(scope.row.productNumber)
        }}</template>
      </el-table-column>
      <el-table-column label="米数(米)" align="center" prop="meters" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 2 ? 'danger' : 'success'">
            <dict-tag
              :options="dict.type.zc_sales_products"
              :value="scope.row.status"
            />
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sales:salesProducts:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sales:salesProducts:remove']"
            >删除</el-button
          >
          <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-star-off"
              @click="handleProductsForm(scope.row)"
            >生成生产计划</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-star-on"
            v-show="scope.row.status == '0'"
            @click="handleProductsForm(scope.row)"
            >生成生产计划
          </el-button>
          <!-- <el-button  
              size="mini"  
              type="text" 
              :icon="productStatus === '已生成' ? 'el-icon-star-on' : 'el-icon-star-off'"  
              :disabled="productStatus === '已生成'"  
              @click="productStatus === '待生成' ? handleProductsForm(scope.row) : null"  
            >  
              {{ productStatus === '已生成' ? '已生成生产计划' : '生成生产计划' }}  
            </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品" prop="productNumber">
          <!-- <el-input v-model="form.salesProductNumber" placeholder="请选择产品编码" /> -->
          <el-select
            v-model="form.productNumber"
            placeholder="请选择要生产的产品"
            filterable
          >
            <el-option
              v-for="item in productsOptions"
              :key="item.productId"
              :label="item.name"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <!-- 如果找不到所需产品，就跳转产品管理进行新增 -->
        <el-form-item label="定制产品" :disabled="isEdit">
          <!-- @click="changeIndex" 点击页面跳转 -->
          <el-button :disabled="isEdit" @click="changeIndex"
            >跳转链接</el-button
          >
        </el-form-item>
        <el-row>
          <el-col :span="11">
            <el-form-item label="米数(米)" prop="meters">
              <el-input
                v-model="form.meters"
                placeholder="请输入米数"
                type="number"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option
                v-for="dict in dict.type.zc_sales_products"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 生成生产计划对话框 -->
    <!-- append-to-body: Dialog 自身是否插入至 body 元素上。嵌套的 Dialog 必须指定该属性并赋值为 true -->
    <el-dialog
      :title="title"
      :visible.sync="productOpen"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品编码" prop="salesProductNumber">
          <el-input
            v-model="form.salesProductNumber"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="productNumber">
          <el-select v-model="form.productNumber" :disabled="true">
            <el-option
              v-for="item in productsOptions"
              :key="item.productId"
              :label="item.name"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="11">
            <el-form-item label="米数(米)" prop="meters">
              <el-input v-model="form.meters" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="产品" prop="productNumber">
            
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="productSubmitForm">确 定</el-button>
        <el-button @click="productCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  listSalesProducts,
  getSalesProducts,
  delSalesProducts,
  addSalesProducts,
  updateSalesProducts,
  productsListSelect,
  productPlan,
} from "@/api/sales/data";
import { salesListSelect, getSalesList } from "@/api/sales/salesList";
export default {
  name: "SalesProducts",
  dicts: ["zc_sales_products"],
  data() {
    var validateMeters = (rule, value, callback) => {
      // 正则表达式，匹配正整数
      const regex = /^\d+$/;
      if (!regex.test(value)) {
        callback(new Error("请输入有效的正整数米数"));
      } else if (value <= 0) {
        callback(new Error("米数必须为正整数"));
      } else {
        callback();
      }
    };
    return {
      productStatus: "待生成", // 用于跟踪生产计划的状态
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售产品表格数据
      salesProductsList: [],
      // 默认编码
      defaultSalesNumber: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      productOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        salesId: this.$route.params && this.$route.params.salesId,
        salesProductNumber: null,
        productNumber: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productNumber: [
          { required: true, message: "产品不能为空", trigger: "blur" },
        ],
        meters: [
          { required: true, validator: validateMeters, trigger: "blur" },
        ],
      },
      //产品选项
      productsOptions: undefined,
      // 添加还是修改
      isEdit: false,
      //销售单
      salesListOptions: [],
      //销售单id
      salesIdFalse: this.$route.params && this.$route.params.salesId,
    };
  },
  created() {
    this.getProductsList();
    this.getSalesListId();
    this.getList();
  },
  methods: {
    //查询销售单列表
    getSalesListId() {
      salesListSelect().then((response) => {
        this.salesListOptions = response.data;
      });
    },
    //页面跳转
    changeIndex() {
      this.$router.push({
        path: "/sales/product",
      });
    },
    getProductName(productNumber) {
      // 遍历 productsOptions 数组以找到匹配的 productNumber
      const foundItem = this.productsOptions.find(
        (item) => item.productId === productNumber
      );
      // 如果找到了匹配的项，返回其 productName，否则返回空字符串或未定义
      return foundItem ? foundItem.name : "";
    },
    /** 查询产品列表 */
    getProductsList() {
      productsListSelect().then((response) => {
        this.productsOptions = response.data;
      });
    },
    /** 查询销售产品列表 */
    getList() {
      this.loading = true;
      listSalesProducts(this.queryParams, this.salesIdFalse).then(
        (response) => {
          this.salesProductsList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    productCancel() {
      this.productOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        // 获取路由的salesId
        salesId: this.$route.params && this.$route.params.salesId,
        productNumber: null,
        salesProductNumber: null,
        meters: null,
        status: "0",
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        del: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = { path: "/money/salesList" };
      this.$tab.closeOpenPage(obj);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.salesProductNumber = this.defaultSalesNumber;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售产品";
      this.form.salesProductNumber = this.queryParams.salesProductNumber;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids;
      getSalesProducts(productId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isEdit = true;
        this.title = "修改销售产品";
      });
    },
    /** 生成生产计划按钮操作 */
    handleProductsForm(row) {
      this.reset();
      getSalesProducts(row.productId).then((response) => {
        this.form = response.data;
        this.productOpen = true;
        this.title = "生成生产计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.productId != null) {
            updateSalesProducts(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSalesProducts(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    productSubmitForm() {
      this.$refs["form"].validate((valid) => {
        productPlan(this.form).then((response) => {
          this.$modal.msgSuccess("生成生产计划成功");
          this.productStatus = "已生成"; // 更新生产计划状态
          this.productOpen = false;
          this.getList();
        });
        // if(valid && this.form.productId != null){

        // }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal
        .confirm('是否确认删除销售产品编号为"' + productIds + '"的数据项？')
        .then(function () {
          return delSalesProducts(productIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "sales/salesProducts/export",
        {
          ...this.queryParams,
        },
        `salesProducts_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
  